﻿// Copyright (C) 2012 Jeff Tanner <jeff00seattle@gmail.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Diagnostics;

namespace WebSlideProjector.EventLogs
{
    using WebSlideProjector.Extensions;

    public class WebEventLog
    {
        protected string LogName { get; private set; }
        protected string LogSource { get; private set; }

        public WebEventLog()
        {
            if (ConfigurationManager.AppSettings["LogName"] != null)
            {
                this.LogName = ConfigurationManager.AppSettings["LogName"];
            }

            if (ConfigurationManager.AppSettings["LogSource"] != null)
            {
                this.LogSource = ConfigurationManager.AppSettings["LogSource"];
            }
        }

        public void LogError(string errorMessage)
        {
            //check if log source exists and create it if it doesn't
            if (!System.Diagnostics.EventLog.SourceExists(this.LogSource, "."))
            {
                System.Diagnostics.EventLog.CreateEventSource(this.LogSource, this.LogName);
            }

            System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(this.LogName, ".", this.LogSource);

            appLog.WriteEntry(errorMessage);
        }

        public void LogException(Exception ex, string origin)
        {
            string errorMessage = ex.ToErrorMessageString();

            //check if log source exists and create it if it doesn't
            if (!System.Diagnostics.EventLog.SourceExists(this.LogSource, "."))
            {
                System.Diagnostics.EventLog.CreateEventSource(this.LogSource, this.LogName);
            }

            System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog(this.LogName, ".", this.LogSource);

            appLog.WriteEntry(String.Format("Error in: {0}\n {1}", origin, errorMessage), EventLogEntryType.Error);
        }
    }
}